﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
using System.ServiceModel;
using System.Threading;

namespace Server
{
    public class Server : IServerContract
    {
        public List<Match> GetMatchs()
        {
            return Program.Matchs;
        }

        public void VoteForPlayer(Player player, Match match)
        {
            Match currentMatch = Program.Matchs.First(x => x.MatchDate == match.MatchDate && x.TeamAway.Name == match.TeamAway.Name && x.TeamHome.Name == match.TeamHome.Name);
            Team team = currentMatch.TeamAway.Players.Any(x => x.FirstName == player.FirstName && x.LastName == player.LastName) ? currentMatch.TeamAway : currentMatch.TeamHome;
            Player p = team.Name == currentMatch.TeamHome.Name ? currentMatch.TeamHome.Players.First(x => x.FirstName == player.FirstName && x.LastName == player.LastName) : currentMatch.TeamAway.Players.First(x => x.FirstName == player.FirstName && x.LastName == player.LastName);
            p.NbVotes++;


            Program.Clients = Program.Clients ?? new List<IClientContract>();
            if (!Program.Clients.Contains(OperationContext.Current.GetCallbackChannel<IClientContract>()))
                Program.Clients.Add(OperationContext.Current.GetCallbackChannel<IClientContract>());

            SendUpdateToClients();
        }

        public void SendUpdateToClients()
        {
            foreach(IClientContract client in Program.Clients)
            {
                Thread t = new Thread((x) => {
                    try
                    {
                        IClientContract clientContract = (IClientContract)x;
                        if (clientContract != null)
                            clientContract.UpdateMatchs(Program.Matchs);
                        else
                            throw new Exception();
                    }
                    catch(Exception e)
                    {
                        //client seems to be disconnected
                        Program.Clients.Remove((IClientContract)x);
                    }
                });
                t.Start(client);
            }
        }
    }
}
